<template>
  <div id="knowledgeGraphPage">
    <a-card :bordered="false" class="main-card">
      <div class="header">
        <h1 class="title">知识图谱</h1>
        <div class="description">
          这里展示了您在答题过程中积累的知识点关联图谱，帮助您了解知识点之间的联系并找出薄弱环节
        </div>
        <div class="control-panel">
          <a-space>
            <a-radio-group
              v-model="mode"
              type="button"
              @change="handleModeChange"
            >
              <a-radio value="all">全部知识点</a-radio>
              <a-radio value="weak">薄弱知识点</a-radio>
            </a-radio-group>
            <a-tooltip content="点击节点可查看详细信息">
              <a-button type="outline" shape="circle">
                <template #icon>
                  <icon-question-circle />
                </template>
              </a-button>
            </a-tooltip>
          </a-space>
        </div>
      </div>

      <a-divider />

      <div v-if="loading" class="loading-container">
        <a-spin tip="知识图谱生成中..." />
      </div>

      <div v-else-if="isEmpty" class="empty-container">
        <a-empty description="暂无知识图谱数据">
          <template #image>
            <img
              src="//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a0082b7754fbdb2d98a5d18501c5c9d6.png~tplv-uwbnlip3yd-webp.webp"
            />
          </template>
          <template #extra>
            <div class="empty-hint">完成更多题目以构建您的知识图谱</div>
          </template>
        </a-empty>
      </div>

      <div v-else class="graph-container">
        <div class="graph-hint" v-if="!detailVisible">
          <a-alert type="info" closable>
            <template #icon>
              <icon-info-circle />
            </template>
            <template #message
              >点击知识点可查看详细信息，拖拽可调整视图
            </template>
          </a-alert>
        </div>
        <v-chart
          class="chart"
          :option="chartOption"
          autoresize
          @click="handleNodeClick"
        />
      </div>

      <a-modal
        v-model:visible="detailVisible"
        :title="currentKnowledge.name"
        width="800px"
        :footer="false"
        :mask-closable="true"
        @cancel="closeDetail"
        class="knowledge-modal"
      >
        <template #title>
          <div class="modal-title">
            <span class="knowledge-name">{{ currentKnowledge.name }}</span>
            <a-tag color="rgb(var(--red-6))" class="error-count">
              <template #icon>
                <icon-exclamation-circle-fill />
              </template>
              出错次数: {{ currentKnowledge.errorCount }}
            </a-tag>
          </div>
        </template>

        <div class="knowledge-detail">
          <a-tabs default-active-key="1" animation>
            <a-tab-pane key="1" title="相关错题">
              <a-empty
                v-if="!currentKnowledge.relatedWrongQuestions?.length"
                description="暂无相关错题"
              />
              <a-list v-else class="question-list" :bordered="false">
                <a-list-item
                  v-for="question in currentKnowledge.relatedWrongQuestions"
                  :key="question.id"
                  class="question-item"
                >
                  <a-list-item-meta>
                    <template #title>
                      <div class="question-title">{{ question.title }}</div>
                    </template>
                    <template #description>
                      <div class="question-info">
                        <a-tag size="small"
                          >用户答案: {{ question.userAnswer }}
                        </a-tag>
                        <span class="question-time">{{
                          formatDate(question.createTime)
                        }}</span>
                      </div>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
            </a-tab-pane>

            <a-tab-pane key="2" title="相关知识点">
              <a-empty
                v-if="!currentKnowledge.relatedKnowledgePoints?.length"
                description="暂无相关知识点"
              />
              <div v-else class="knowledge-points">
                <a-tag
                  v-for="point in currentKnowledge.relatedKnowledgePoints"
                  :key="point"
                  color="blue"
                  class="knowledge-tag"
                  @click="searchKnowledgePoint(point)"
                >
                  {{ point }}
                </a-tag>
              </div>
            </a-tab-pane>

            <a-tab-pane key="3" title="推荐学习资源">
              <a-empty
                v-if="!currentKnowledge.resources?.length"
                description="暂无推荐学习资源"
              />
              <a-list v-else :bordered="false" class="resource-list">
                <a-list-item
                  v-for="resource in currentKnowledge.resources"
                  :key="resource.title"
                  class="resource-item"
                >
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar
                        shape="square"
                        :style="{
                          backgroundColor: getResourceColor(resource.type),
                        }"
                      >
                        <icon-file v-if="resource.type === '文章'" />
                        <icon-video-camera
                          v-else-if="resource.type === '视频'"
                        />
                        <icon-desktop v-else-if="resource.type === '课程'" />
                        <icon-search v-else />
                      </a-avatar>
                    </template>
                    <template #title>
                      <a
                        :href="resource.url"
                        target="_blank"
                        class="resource-link"
                        >{{ resource.title }}</a
                      >
                    </template>
                    <template #description>
                      <a-tag color="green" size="small"
                        >{{ resource.type }}
                      </a-tag>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </a-list>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { use } from "echarts/core";
import { GraphChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import {
  getKnowledgeGraphUsingGet,
  getKnowledgeDetailUsingGet,
} from "@/api/knowledgeGraphController";
import { useLoginUserStore } from "@/store/userStore";
import message from "@arco-design/web-vue/es/message";
import dayjs from "dayjs";
import VChart from "vue-echarts";

// 注册必须的组件
use([
  GraphChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
]);

// 图表模式：全部/薄弱
const mode = ref<"all" | "weak">("all");
// 知识图谱数据
const knowledgeGraphData = ref<API.KnowledgeGraphVO>({
  nodes: [],
  links: [],
});
// 加载状态
const loading = ref(true);
// 用户信息
const userStore = useLoginUserStore();
// 是否显示详情弹窗
const detailVisible = ref(false);
// 当前选中的知识点详情
const currentKnowledge = ref<API.KnowledgeDetailVO>({
  name: "",
  errorCount: 0,
  relatedKnowledgePoints: [],
  relatedWrongQuestions: [],
  resources: [],
});

// 判断图谱是否为空
const isEmpty = computed(() => {
  return (
    !knowledgeGraphData.value.nodes ||
    knowledgeGraphData.value.nodes.length === 0
  );
});

// 图表配置
const chartOption = computed(() => {
  return {
    title: {
      text: mode.value === "all" ? "知识点关联图谱" : "薄弱知识点关联图谱",
      top: "top",
      left: "center",
      textStyle: {
        fontSize: 18,
        fontWeight: "normal",
        color: "rgb(var(--primary-6))",
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        if (params.dataType === "node") {
          return `<div style="padding: 4px 8px;">
            <div style="font-weight: bold; margin-bottom: 4px; font-size: 14px;">${
              params.data.name
            }</div>
            <div style="font-size: 12px;">错误次数: <span style="color: #ee6666; font-weight: bold;">${
              params.data.errorCount || 0
            }</span></div>
            <div style="font-size: 12px; margin-top: 4px; opacity: 0.7;">点击查看详情</div>
          </div>`;
        } else if (params.dataType === "edge") {
          return `<div style="padding: 4px 8px;">
            <div style="font-size: 13px;">关联强度: <span style="font-weight: bold;">${
              params.data.value || 1
            }</span></div>
          </div>`;
        }
        return "";
      },
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "rgba(0, 0, 0, 0.1)",
      textStyle: {
        color: "#333",
      },
      extraCssText:
        "box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); border-radius: 4px;",
    },
    legend: {
      show: false,
    },
    animationDurationUpdate: 1000,
    animationEasingUpdate: "quinticInOut" as const,
    series: [
      {
        type: "graph",
        layout: "force",
        force: {
          repulsion: 1500,
          gravity: 0.1,
          edgeLength: [80, 200],
          layoutAnimation: true,
        },
        roam: true,
        draggable: true,
        selectedMode: "single",
        label: {
          show: true,
          position: "right",
          formatter: "{b}",
          fontSize: 12,
          fontWeight: "bold",
          color: "#333",
          backgroundColor: "rgba(255, 255, 255, 0.7)",
          padding: [3, 5],
          borderRadius: 3,
        },
        edgeLabel: {
          show: false,
          formatter: "{c}",
          fontSize: 10,
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#fff",
        },
        emphasis: {
          focus: "adjacency",
          lineStyle: {
            width: 5,
            opacity: 0.9,
            curveness: 0.25,
          },
          label: {
            fontSize: 13,
            backgroundColor: "rgba(255, 255, 255, 0.9)",
          },
          itemStyle: {
            shadowColor: "rgba(0, 0, 0, 0.3)",
            shadowBlur: 10,
          },
        },
        data:
          knowledgeGraphData.value.nodes?.map((node) => ({
            id: node.id,
            name: node.name,
            symbolSize: getNodeSize(node.errorCount || 0, node.value || 30),
            value: node.value,
            errorCount: node.errorCount,
            itemStyle: {
              color: getNodeColor(node.errorCount || 0),
              shadowColor: "rgba(0, 0, 0, 0.2)",
              shadowBlur: 5,
            },
          })) || [],
        links:
          knowledgeGraphData.value.links?.map((link) => ({
            source: link.source,
            target: link.target,
            value: link.value,
            symbolSize: [3, 6],
            lineStyle: {
              width: Math.max(1, Math.min(5, link.value || 1)),
              opacity: 0.7,
              curveness: 0.2,
            },
          })) || [],
        lineStyle: {
          color: "rgb(var(--primary-5))",
          opacity: 0.6,
          width: 1.5,
          curveness: 0.2,
        },
      },
    ],
  };
});

/**
 * 根据错误次数获取节点大小
 */
const getNodeSize = (errorCount: number, baseSize: number) => {
  // 确保节点大小随错误次数增加而增大，但有一个上限
  const minSize = Math.max(30, baseSize);
  const sizeIncrement = errorCount * 5;
  return Math.min(minSize + sizeIncrement, 70);
};

/**
 * 根据错误次数获取节点颜色
 */
const getNodeColor = (errorCount: number) => {
  if (errorCount <= 1) return "rgba(102, 194, 165, 0.9)"; // 绿色 - 掌握良好
  if (errorCount <= 3) return "rgba(252, 141, 98, 0.9)"; // 橙色 - 需要巩固
  return "rgba(220, 57, 18, 0.9)"; // 红色 - 薄弱知识点
};

/**
 * 获取资源类型对应的颜色
 */
const getResourceColor = (type: string | undefined) => {
  if (!type) return "rgb(var(--primary-6))";

  switch (type) {
    case "文章":
      return "rgb(var(--blue-6))";
    case "视频":
      return "rgb(var(--orange-6))";
    case "课程":
      return "rgb(var(--green-6))";
    default:
      return "rgb(var(--primary-6))";
  }
};

/**
 * 加载知识图谱数据
 */
const loadKnowledgeGraph = async () => {
  loading.value = true;
  try {
    const userId = userStore.loginUser?.id;
    if (!userId) {
      message.error("请先登录");
      loading.value = false;
      return;
    }

    const res = await getKnowledgeGraphUsingGet({
      userId: userId as number,
      mode: mode.value,
    });

    if (res.data.code === 0) {
      knowledgeGraphData.value = res.data.data || { nodes: [], links: [] };
      console.log("知识图谱数据:", knowledgeGraphData.value);
    } else {
      message.error("获取知识图谱失败：" + res.data.message);
    }
  } catch (error) {
    console.error("加载知识图谱失败", error);
    message.error("加载知识图谱失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

/**
 * 处理模式切换
 */
const handleModeChange = () => {
  loadKnowledgeGraph();
};

/**
 * 处理节点点击
 */
const handleNodeClick = async (params: any) => {
  if (params.dataType !== "node") return;

  try {
    const userId = userStore.loginUser?.id;
    if (!userId) {
      message.error("请先登录");
      return;
    }

    const knowledgePoint = params.data.name;
    const res = await getKnowledgeDetailUsingGet({
      userId: userId as number,
      knowledgePoint,
    });

    if (res.data.code === 0) {
      currentKnowledge.value = res.data.data || {
        name: knowledgePoint,
        errorCount: 0,
        relatedKnowledgePoints: [],
        relatedWrongQuestions: [],
        resources: [],
      };
      detailVisible.value = true;
    } else {
      message.error("获取知识点详情失败：" + res.data.message);
    }
  } catch (error) {
    console.error("获取知识点详情失败", error);
    message.error("获取知识点详情失败，请稍后重试");
  }
};

/**
 * 查询相关知识点
 */
const searchKnowledgePoint = (knowledgePoint: string) => {
  // 如果相关知识点被点击，可以查询该知识点的详情
  const userId = userStore.loginUser?.id;
  if (!userId) {
    message.error("请先登录");
    return;
  }

  getKnowledgeDetailUsingGet({
    userId: userId as number,
    knowledgePoint,
  })
    .then((res) => {
      if (res.data.code === 0) {
        currentKnowledge.value = res.data.data || {
          name: knowledgePoint,
          errorCount: 0,
          relatedKnowledgePoints: [],
          relatedWrongQuestions: [],
          resources: [],
        };
      }
    })
    .catch((error) => {
      console.error("获取相关知识点详情失败", error);
      message.error("获取相关知识点详情失败");
    });
};

/**
 * 关闭详情弹窗
 */
const closeDetail = () => {
  detailVisible.value = false;
};

/**
 * 格式化日期
 */
const formatDate = (date: string | undefined) => {
  if (!date) return "";
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 页面加载时获取知识图谱数据
onMounted(() => {
  loadKnowledgeGraph();
});
</script>

<style scoped>
#knowledgeGraphPage {
  padding: 16px;
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
  background: linear-gradient(to bottom, #ffffff, #f9faff);
  transition: all 0.3s ease;
}

.main-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.header {
  margin-bottom: 24px;
  padding: 4px 0 12px;
}

.title {
  font-size: 28px;
  margin-bottom: 12px;
  color: rgb(var(--primary-6));
  font-weight: 600;
  letter-spacing: 0.5px;
  position: relative;
  display: inline-block;
}

.title::after {
  content: "";
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 40px;
  height: 3px;
  background-color: rgb(var(--primary-6));
  border-radius: 2px;
}

.description {
  color: rgb(var(--gray-8));
  margin-bottom: 20px;
  font-size: 15px;
  line-height: 1.6;
  max-width: 800px;
}

.control-panel {
  margin: 20px 0;
  display: flex;
  align-items: center;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 500px;
  color: rgb(var(--gray-6));
}

.empty-hint {
  margin-top: 12px;
  color: rgb(var(--gray-6));
  font-size: 14px;
}

.graph-container {
  width: 100%;
  height: 650px;
  position: relative;
  border-radius: 8px;
  background: linear-gradient(135deg, #f5f7ff 0%, #f8faff 100%);
  border: 1px solid rgba(var(--gray-3), 0.5);
  overflow: hidden;
  transition: all 0.3s ease;
}

.graph-container:hover {
  border-color: rgba(var(--primary-5), 0.5);
  box-shadow: 0 0 15px rgba(var(--primary-2), 0.3);
}

.graph-hint {
  position: absolute;
  top: 10px;
  right: 16px;
  z-index: 10;
  max-width: 300px;
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.graph-hint:hover {
  opacity: 1;
}

.chart {
  width: 100%;
  height: 100%;
}

.knowledge-modal :deep(.arco-modal-header) {
  border-bottom: 1px solid rgba(var(--gray-3), 0.6);
  padding: 16px 20px;
}

.modal-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.knowledge-name {
  font-size: 18px;
  font-weight: 600;
  color: rgb(var(--primary-6));
}

.error-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.knowledge-detail {
  padding: 12px 0;
}

.knowledge-points {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 8px 0;
}

.knowledge-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 4px;
}

.knowledge-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(var(--blue-5), 0.3);
}

.question-list {
  max-height: 400px;
  overflow-y: auto;
}

.question-item {
  border-bottom: 1px solid rgba(var(--gray-3), 0.3);
  padding: 12px 0;
  transition: background-color 0.2s ease;
}

.question-item:hover {
  background-color: rgba(var(--primary-1), 0.2);
}

.question-title {
  font-weight: 500;
  color: rgb(var(--gray-10));
  margin-bottom: 6px;
}

.question-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-time {
  font-size: 12px;
  color: rgb(var(--gray-6));
}

.resource-list {
  max-height: 400px;
  overflow-y: auto;
}

.resource-item {
  padding: 12px 0;
  transition: all 0.2s ease;
  border-bottom: 1px solid rgba(var(--gray-3), 0.3);
}

.resource-item:hover {
  background-color: rgba(var(--primary-1), 0.2);
}

.resource-link {
  color: rgb(var(--primary-6));
  text-decoration: none;
  transition: color 0.2s ease;
}

.resource-link:hover {
  color: rgb(var(--primary-7));
  text-decoration: underline;
}
</style>
